package tech.aistar.corejava.day14.homework;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * @Author: lya
 * @Description: 本类的作用描述:
 * @CreateDate: 2019/8/5
 * @Version: 1.0
 */
public class CountLetterDemo {
    public static void main(String[] args) {
        Path letter = Paths.get("src/tech/aistar/corejava/day14/homework/letter.txt");
        try {
            List<String> lines = Files.readAllLines(letter);

            //定义一个Map集合
            //key - 字母
            //value - 字母出现的次数
            Map<Character,Integer> map = new HashMap<>();

            for (String n : lines) {
                //将字符串转成字符数组
                char[] arr = n.toCharArray();
                for (int i = 0; i < arr.length; i++) {
                    //判断map集合中是否包含key
                    if (map.containsKey(arr[i])){
                        map.put(arr[i],map.get(arr[i] + 1));
                    }else{
                        map.put(arr[i],1);
                    }
                }
            }
            List<Map.Entry<Character,Integer>> sortList = new ArrayList<>();

            Set<Map.Entry<Character,Integer>> entrySet = map.entrySet();

            Iterator<Map.Entry<Character,Integer>> iter = entrySet.iterator();

            while(iter.hasNext()){
                sortList.add(iter.next());
            }

            Collections.sort(sortList,(o1,o2)->{
                if (o1.getValue()>o2.getValue()){
                    return  -1;
                }else if(o1.getValue()<o2.getValue()){
                    return o2.getKey().compareTo(o1.getKey());
                }else{
                    return 1;
                }
            });

            sortList.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
